//
//  HealthOxygenViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/13.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "HealthOxygenViewController.h"
#import "HealthHeadTableViewCell.h"
#import "OxygenChartView.h"
#import "NSString+Helper.h"

@interface HealthOxygenViewController ()

@end

@implementation HealthOxygenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.count = @"0";
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [self setSelectImage];
    UILabel *lab = [self.view viewWithTag:10];
    lab.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@%%",self.count] perUnitLength:1];
}

#pragma mark - 数据请求
- (void)getHealthData:(NSString *)startDate endDate:(NSString *)endDate{
    [SVProgressHUD showWithStatus:@"获取血氧数据.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:startDate forKey:@"start_date"];
    [dict setObject:endDate forKey:@"end_date"];
    [dict setObject:@"6" forKey:@"health_type"];
    [[BaseDataRequest alloc] getDetailedHealthData:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]){
            self.arrYAxis =[NSMutableArray array];
            NSMutableDictionary *result = [responseObject objectForKey:@"result"];
            NSMutableDictionary *dataModel = [result objectForKey:@"data"];
            if([dataModel allKeys].count == 0){
                TIPSFORVIEW(@"暂无数据");
                self.requestDateType = self.previousDateType;
                return ;
            }
            self.previousDateType = self.requestDateType;
            NSMutableArray *keys = [NSMutableArray arrayWithArray:[dataModel allKeys]];
            [keys sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                if ([obj1 integerValue] > [obj2 integerValue]) {
                    return NSOrderedDescending;
                }else if ([obj1 integerValue] < [obj2 integerValue]){
                    return NSOrderedAscending;
                }else {
                    return NSOrderedSame;
                }
            }];
            [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (self.requestDateType == RequestBreatheTypeDay) {
                    NSString *time ;
                    time = [obj substringToIndex:2];
                    NSString *minute ;
                    minute = [obj substringFromIndex:2];
                    int index = ([time intValue]*12) + ([minute intValue]/5);
                    NSDictionary *model = [dataModel objectForKey:obj];
                    [self.arrModel replaceObjectAtIndex:index withObject:[model objectForKey:@"avg"]];
                    [self.arrMax replaceObjectAtIndex:index withObject:[model objectForKey:@"max"]];
                    [self.arrMin replaceObjectAtIndex:index withObject:[model objectForKey:@"min"]];
                }else{
                    NSMutableString *str = [[NSMutableString alloc]initWithFormat:@"%@",obj];
                    [str insertString:@"/"atIndex:2];
                    for (int i = 0; i < self.arrXAxisMark.count; i++) {
                        if ([self.arrXAxisMark[i] isEqualToString:str]) {
                            NSDictionary *model = [dataModel objectForKey:obj];
                            [self.arrModel replaceObjectAtIndex:i withObject:[model objectForKey:@"avg"]];
                            [self.arrMax replaceObjectAtIndex:i withObject:[model objectForKey:@"max"]];
                            [self.arrMin replaceObjectAtIndex:i withObject:[model objectForKey:@"min"]];
                        }
                    }
                }
            }];
            self.count = self.arrModel[[self backIndex:self.arrModel]];
            self.arrYAxis =[self.arrModel copy];
            [self.tableView reloadData];
            [self setSelectImage];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"获取血氧数据失败");
            }
        }
    }];
}

#pragma mark -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.row == 0){
        static NSString *cellidentify = @"HealthHeadTableViewCell";
        HealthHeadTableViewCell *cell = (HealthHeadTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellidentify];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"HealthHeadTableViewCell" owner:self options:nil] objectAtIndex:0];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell.btnDay addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnWeek addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnMonth addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnSelectData addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.imageType.image = [UIImage imageNamed:@"icon_oxygensaturation"];
        //cell.labelNumber.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@%%",self.count ] perUnitLength:1];
        if (self.arrYAxis.count != 0) {
            NSMutableArray *arr = [NSMutableArray array];
            for (int i = 0; i < self.arrYAxis.count; i++) {
                if (![self.arrYAxis[i] isEqualToString:@"-1"]) {
                    [arr addObject:self.arrYAxis[i]];
                }
            }
            cell.labValueOne.text = [NSString stringWithFormat:@"%.f %%",[[arr valueForKeyPath:@"@max.floatValue"] floatValue]];
            cell.labValueTwo.text = [NSString stringWithFormat:@"%.f %%",[[arr valueForKeyPath:@"@min.floatValue"] floatValue]];
            cell.labValueS.text = [NSString stringWithFormat:@"%.f %%",[[arr valueForKeyPath:@"@avg.floatValue"] floatValue]];
        }
        cell.labeUnitOne.text = @"血氧最高值";
        cell.labUnitTwo.text = @"血氧最低值";
        cell.labUnitS.text = @"血氧平均值";
        self.imageSelect = cell.imageSelect;
        cell.labData.text = [NSString stringThatDay:self.selectDate];
        cell.viewSleep.hidden = YES;
        UILabel *labTime = [cell viewWithTag:111];
        if (self.requestDateType == RequestBreatheTypeDay) {
            labTime.text = [NSString stringTime:self.selectDate];
        }else if(self.requestDateType == RequestBreatheTypeWeek){
            labTime.text = [NSString stringWeek:[NSDate date]];
        }else{
            labTime.text = [NSString stringMonth:[NSDate date]];
        }
        return cell;
    }else if(indexPath.row == 1){
        UITableViewCell *cell ;
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HealthBreatheViewCell1"] ;
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        if (self.arrYAxis.count != 0) {
            self.breatheView = [[OxygenChartView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
            self.breatheView.delegate = self;
            NSMutableArray *arrY      = [NSMutableArray arrayWithObjects:@"70",@"80",@"90",@"100",nil];
            int type = self.requestDateType;
            self.breatheView.shadowStart = 90;
            self.breatheView.shadowEnd = 100;
            if(self.requestDateType == RequestBreatheTypeAge){
                NSMutableArray *arrExtraction = [NSMutableArray array];
                int index = 0;
                while (index < self.arrXAxisMark.count) {
                    [arrExtraction addObject:self.arrXAxisMark[index]];
                    index += 4;
                }
                self.breatheView.xAxisMark  = arrExtraction;
            }else{
                self.breatheView.xAxisMark  = self.arrXAxisMark;
            }
            self.breatheView.yAxisMark  = arrY;
            self.breatheView.yAxis      = self.arrYAxis;
            self.breatheView.baseChartType = self.brokenLine?BaseChartTypeHistogram:BaseChartTypeLineChart;
            self.breatheView.baseChartShowDate  = type;
            self.breatheView.baseChartShowDateType = BaseChartShowDateTypeOxygen;
            [self.breatheView startDraw];
            [cell.contentView addSubview:self.breatheView];
        }
        return cell;
    }else{
        static NSString *cellidentify = @"HealthFootTableViewCell";
        HealthFootTableViewCell *cell = (HealthFootTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellidentify];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"HealthFootTableViewCell" owner:self options:nil] objectAtIndex:0];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell.btnSelectType addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.btnMeasuring.hidden = YES;//蓝牙隐藏
        return cell;
    }
}

#pragma mark - BaseChartViewDelegate
- (void)backData:(NSString *)number withTime:(NSString *)time{
    self.count = number;
    UILabel *lab = [self.view viewWithTag:10];
    UILabel *labDate = [self.view viewWithTag:13];
    UILabel *labTime = [self.view viewWithTag:111];
    lab.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@%%",number] perUnitLength:1];
    if (self.requestDateType == RequestBreatheTypeDay) {
        labTime.text = [NSString stringWithFormat:@"%@ %@",[NSString stringTime:self.selectDate],time];
    }else{
        labDate.text = [NSString stringThatDay:[NSString stringToDate:time]];
        labTime.text = time;
    }
}

- (void)backIndex:(int)number withTime:(NSString *)time{
    UILabel *lab = [self.view viewWithTag:10];
    UILabel *labDate = [self.view viewWithTag:13];
    UILabel *labTime = [self.view viewWithTag:111];
    lab.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@%%",self.arrYAxis[number]] perUnitLength:1];
    if (self.requestDateType == RequestBreatheTypeDay) {
        labTime.text = [NSString stringWithFormat:@"%@ %@",[NSString stringTime:self.selectDate],time];
    }else{
        labDate.text = [NSString stringThatDay:[NSString stringToDate:time]];
        labTime.text = time;
    }
    UILabel *labOne = [self.view viewWithTag:1111];
    labOne.text = [NSString stringWithFormat:@"%@%%",self.arrMax[number] ];
    UILabel *labTwo = [self.view viewWithTag:2222];
    labTwo.text = [NSString stringWithFormat:@"%@%%",self.arrMin[number] ];
    UILabel *labS = [self.view viewWithTag:3333];
    labS.text = [NSString stringWithFormat:@"%@%%",self.arrYAxis[number]];
}

#pragma mark - 
- (void)arrModelDataFill{
    [self.arrModel removeAllObjects];
    [self.arrMax removeAllObjects];
    [self.arrMin removeAllObjects];
    if (self.requestDateType == RequestBreatheTypeDay) {
        int i = 0;
        while ( i < 288) {
            [self.arrModel addObject:@"-1"];
            [self.arrMin addObject:@"-1"];
            [self.arrMax addObject:@"-1"];
            i ++;
        }
    }else if (self.requestDateType == RequestBreatheTypeWeek){
        for (int i = 0; i < 7; i++) {
            [self.arrModel addObject:@"70"];
            [self.arrMin addObject:@"70"];
            [self.arrMax addObject:@"70"];
        }
    }else{
        for (int i = 0; i < 29; i++) {
            [self.arrModel addObject:@"70"];
            [self.arrMin addObject:@"70"];
            [self.arrMax addObject:@"70"];
        }
    }
}

- (void)helpAction{
    GlossaryViewController *glossary = [[GlossaryViewController alloc] initWithNibName:@"GlossaryViewController" bundle:nil];
    glossary.strTitle = @"血氧";
    [self.navigationController pushViewController:glossary animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
